<template>
  <el-dialog
    title="跨表条件"
    width="800px"
    :show-close="true"
    :visible.sync="crossVisible"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <div style="height: 180px">
      <!-- 🏀多层 -->
      <div style="margin-bottom: 8px" v-for="(item, index) in crossObjArrValue" :key="index">
        <!-- 0. 删除标志 -->
        <i class="el-icon-delete" style="margin-right: 4px" @click="btnCrossConditionDel(item.id)"></i>
        <!-- 并联条件下拉框 -->
        <el-select v-if="item.zero" size="mini" style="width: 10%; margin-right: 4px" v-model="item.zero">
          <el-option
            v-for="it in tableConditionOptionsZero"
            :key="it.value"
            :value="it.value"
            :label="it.label"
          ></el-option>
        </el-select>
        <!-- 1. 访视 -->
        <el-select
          v-model="item.interview"
          size="mini"
          style="width: 15%; margin-right: 4px"
          placeholder="选择访视"
          @change="onInterviewChange($event, index)"
        >
          <el-option v-for="it in interviewOptions" :key="it.id" :label="it.visitName" :value="it.id"></el-option>
        </el-select>
        <!-- 2. 表单 -->
        <el-select
          v-model="item.form"
          size="mini"
          style="width: 15%; margin-right: 4px"
          placeholder="选择表单"
          @change="onFormChange($event, index)"
        >
          <el-option v-for="it in item.formOptions" :key="it.id" :label="it.visitTableName" :value="it.id"> </el-option>
        </el-select>
        <!-- 3. 字段 -->
        <el-select
          v-model="item.word"
          size="mini"
          style="width: 15%; margin-right: 4px"
          placeholder="选择字段"
          @change="handleWordChange($event, index)"
        >
          <el-option v-for="it in item.wordOptions" :key="it.variable" :label="it.variableName" :value="it.variable">
          </el-option>
        </el-select>
        <template v-if="item.word">
          <!-- 4. 等于小于 -->
          <el-select v-model="item.firstSelect" size="mini" style="width: 10%; margin-right: 4px">
            <el-option label="等于" value="=="></el-option>
            <el-option label="不等于" value="!="></el-option>
            <el-option label="为空" value="为空"></el-option>
            <el-option label="不为空" value="不为空"></el-option>
            <el-option label="大于" value=">"></el-option>
            <el-option label="小于" value="<"></el-option>
            <el-option label="大于等于" value=">="></el-option>
            <el-option label="小于等于" value="<="></el-option>
          </el-select>
          <!-- 为空不为空变化 -->
          <template v-if="item.firstSelect !== '为空' && item.firstSelect !== '不为空'">
            <!-- 5. 变量具体值 -->
            <el-select
              v-model="item.secondSelect"
              size="mini"
              style="width: 15%; margin-right: 4px"
              @change="handleVariableConcreteValue($event, index)"
            >
              <el-option label="与变量比较" value="与变量比较"></el-option>
              <el-option label="与具体值比较" value="与具体值比较"></el-option>
            </el-select>
            <!-- 变化一 -->
            <template v-if="item.secondSelect === '与变量比较'">
              <!-- 访视 -->
              <el-select
                v-model="item.interviewTwo"
                size="mini"
                style="width: 15%; margin-right: 4px"
                placeholder="选择访视"
                @change="onInterviewChangeTwo($event, index)"
              >
                <el-option v-for="it in interviewOptions" :key="it.id" :label="it.visitName" :value="it.id"></el-option>
              </el-select>
              <!-- 表单 -->
              <el-select
                v-model="item.formTwo"
                size="mini"
                style="width: 15%; margin-right: 4px"
                placeholder="选择表单"
                @change="onFormChangeTwo($event, index)"
              >
                <el-option v-for="it in item.formOptionsTwo" :key="it.id" :label="it.visitTableName" :value="it.id">
                </el-option>
              </el-select>
              <!-- 字段 -->
              <el-select
                v-model="item.wordTwo"
                size="mini"
                style="width: 15%; margin-right: 4px"
                placeholder="选择字段"
              >
                <el-option
                  v-for="it in item.wordOptionsTwo"
                  :key="it.variable"
                  :label="it.variableName"
                  :value="it.variable"
                >
                </el-option>
              </el-select>
            </template>
            <!-- 变化二 -->
            <template v-if="item.secondSelect === '与具体值比较'">
              <!-- 变化二里面的变化一 -->
              <template v-if="!item.variableType">
                <el-input size="mini" style="width: 15%; margin-right: 4px" v-model="item.third"></el-input>
                <el-select size="mini" style="width: 10%; margin-right: 4px" v-model="item.fourth">
                  <el-option label="数值" value="数值"></el-option>
                  <el-option label="字符" value="字符"></el-option>
                </el-select>
              </template>
              <!-- 变化二里面的变化二 -->
              <el-select
                size="mini"
                style="width: 15%; margin-right: 4px"
                v-model="item.fifth"
                v-if="item.variableType === '1020'"
              >
                <el-option
                  v-for="item in item.fifthOptions"
                  :label="item.codeDescribe"
                  :value="item.codeValue"
                  :key="item.codeValue"
                ></el-option>
              </el-select>
            </template>
          </template>
        </template>
      </div>
      <!-- 🏀增加条件按钮层 -->
      <div style="display: flex; justify-content: start">
        <el-button size="mini" type="primary" @click="btnCrossConditionAddCon()">增加条件</el-button>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">取 消</el-button>
      <el-button size="small" type="primary" @click="handleSave">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { mapActions } from 'vuex'
import { checkPropertiesNotEmpty } from '@/utils/modules/tableConLogic.js'
import { btnCrossConditionAddConPublic, btnTableConditionConfirmCrossPublic } from '@/utils/modules/crossConLogic.js'
import { cloneDeep } from 'lodash-es'

export default {
  props: {
    rowData: Object,
    crossVisible: Boolean,
    actionType: String,
  },
  data() {
    return {
      // 跨表下拉框开始💭🏀
      crossObjArrValue: [],
      interviewOptions: [],
      interviewOptionseEnums: {},
      crossConId: '',
      wordOptionsEnums: {},
      tableConditionOptionsTwoEnums: {
        '==': '等于',
        '!=': '不等于',
        为空: '为空',
        不为空: '不为空',
        '>': '大于',
        '<': '小于',
        '>=': '大于等于',
        '<=': '小于等于',
      },
      tableConditionOptionsZero: [
        { label: '并且', value: '&&' },
        { label: '或者', value: '||' },
      ],
      tableConditionOptionsZeroEnums: {
        '&&': '并且',
        '||': '或者',
      },
      searchParams: {},
      fifthOptionsEnums: {},
      // 跨表下拉框结束💭 🏀
    }
  },

  watch: {
    crossVisible(val) {
      if (val) {
        this.btnCrossConditionOptions(this.rowData)
      }
    },
  },

  mounted() {
    const databaseInfo = JSON.parse(localStorage.getItem('sys-database-info')) || {}
    this.searchParams = {
      projectId: localStorage.getItem('sys-project-id') || '',
      ...databaseInfo,
    }
  },

  methods: {
    ...mapActions('verificationRule', [
      'getNowConfigVisitAPI', // 跨表访视
      'getVisitTableListAPI', // 跨表表单
    ]),
    ...mapActions('eCRFDesign', ['qryCodeValueByCodeNameNoLoading']),

    ...mapActions('eCRFDesign', ['qryVariableConfigListNoLoading']),

    handleClose() {
      this.crossObjArrValue = []
      this.$emit('handleCrossTableConditionCancel')
    },

    // 跨表条件开始💭🏀
    // 10. 字段一Change
    async handleWordChange(val, index) {
      // 判断字段是否为单选或者多选
      const obj = this.crossObjArrValue[index].wordOptions.find(item => item.variable === val)
      if (['10', '20'].includes(obj.variableType)) {
        // 控制fifth的显示和隐藏
        this.crossObjArrValue[index].variableType = '1020'
        // 获取表的tableCode
        const objForm = this.crossObjArrValue[index].formOptions.find(
          item => item.id === this.crossObjArrValue[index].form
        )
        // 发送请求，获取fifthOptions下拉项
        const params = {
          ...this.searchParams,
          code_name: val,
          surface: objForm.tableCode,
        }
        const res = await this.qryCodeValueByCodeNameNoLoading({ params })
        this.crossObjArrValue[index].fifthOptions = res.data
        res.data.forEach(item => {
          this.fifthOptionsEnums[item.codeValue] = item.codeDescribe
        })
      } else {
        this.crossObjArrValue[index].variableType = ''
      }
    },

    // 9. 变量具体值Change
    async handleVariableConcreteValue(val, index) {
      if (val === '与具体值比较') {
        // 判断字段是否为单选或者多选
        const obj = this.crossObjArrValue[index].wordOptions.find(
          item => item.variable === this.crossObjArrValue[index].word
        )
        if (['10', '20'].includes(obj.variableType)) {
          // 控制fifth的显示和隐藏
          this.crossObjArrValue[index].variableType = '1020'
          // 获取表的tableCode
          const objForm = this.crossObjArrValue[index].formOptions.find(
            item => item.id === this.crossObjArrValue[index].form
          )
          // 发送请求，获取fifthOptions下拉项
          const params = {
            ...this.searchParams,
            code_name: obj.variable,
            surface: objForm.tableCode,
          }
          const res = await this.qryCodeValueByCodeNameNoLoading({ params })
          this.crossObjArrValue[index].fifthOptions = res.data
        } else {
          this.crossObjArrValue[index].variableType = ''
        }
      }
    },
    // 8. 点击确认按钮
    async handleSave() {
      const arr = cloneDeep(this.crossObjArrValue)
      //  将表的id转换成tableCode
      arr.forEach(item => {
        if (item.form && item.formOptions.length !== 0) {
          const formOneObj = item.formOptions.find(it => it.id === item.form)
          item.form = formOneObj.tableCode
        }
        if (item.formTwo && item.formOptionsTwo.length !== 0) {
          const formTwoObj = item.formOptionsTwo.find(it => it.id === item.formTwo)
          item.formTwo = formTwoObj.tableCode
        }
      })
      const arrDeep = cloneDeep(arr)
      // 1. 进行非空校验
      arr.forEach(item => {
        if (item.firstSelect === '为空' || item.firstSelect === '不为空') {
          delete item.interviewTwo
          delete item.interviewwordOptionsTwoTwo
          delete item.wordTwo
          delete item.formOptionsTwo
          delete item.formTwo
          delete item.third
          delete item.fourth
          delete item.fifthOptions
          delete item.fifth
          delete item.variableType
        } else {
          if (item.secondSelect === '与变量比较') {
            delete item.third
            delete item.fourth
            delete item.fifthOptions
            delete item.fifth
            delete item.variableType
          } else if (item.secondSelect === '与具体值比较') {
            delete item.interviewTwo
            delete item.interviewwordOptionsTwoTwo
            delete item.wordTwo
            delete item.formOptionsTwo
            delete item.formTwo
            if (item.variableType === '1020') {
              delete item.third
              delete item.fourth
            } else {
              delete item.fifthOptions
              delete item.fifth
              delete item.variableType
            }
          }
        }
      })
      const isNotEmpty = checkPropertiesNotEmpty(arr)
      console.log(isNotEmpty, 'isNotEmpty')
      // 2. 拼接字段
      if (isNotEmpty) {
        const { paramsString, paramsStringTwo } = btnTableConditionConfirmCrossPublic(
          arrDeep,
          this.wordOptionsEnums,
          this.tableConditionOptionsZeroEnums,
          this.tableConditionOptionsTwoEnums,
          this.interviewOptionseEnums,
          this.fifthOptionsEnums
        )
        // 发送请求
        const data = {
          id: this.crossConId,
          crossTable: paramsString,
          crossTableCn: paramsStringTwo,
          crossTableWeb: {
            web: JSON.stringify(arrDeep),
          },
        }
        const res = await this.$store.dispatch(`verificationRule/${this.actionType}`, { data })
        if (res.code === 200) {
          this.crossObjArrValue = []
          this.$emit('handleCrossTableConditionCancel', 'refresh')
        }
      } else {
        this.$message.warning('请填写完整！')
      }
    },
    // 7. poover弹出层隐藏后清空数据
    handlePopoverHideCross() {
      this.crossObjArrValue = []
    },
    // 6. 点击图标删除
    btnCrossConditionDel(id) {
      this.crossObjArrValue = this.crossObjArrValue.filter(item => {
        return item.id !== id
      })
    },
    // 5. 表单选择
    async onFormChange(val, index) {
      const obj = this.crossObjArrValue[index].formOptions.find(item => item.id === val)
      const surface = obj.tableCode
      const params = {
        ...this.searchParams,
        surface: surface,
      }
      const res = await this.qryVariableConfigListNoLoading({ params })
      if (res.code === 200) {
        this.crossObjArrValue[index].word = ''
        this.crossObjArrValue[index].wordOptions = res.data
        res.data.forEach(item => {
          this.wordOptionsEnums[item.variable] = item.variableName
        })
      }
    },
    async onFormChangeTwo(val, index) {
      const obj = this.crossObjArrValue[index].formOptionsTwo.find(item => item.id === val)
      const surface = obj.tableCode
      const params = {
        ...this.searchParams,
        surface: surface,
      }
      const res = await this.qryVariableConfigListNoLoading({ params })
      if (res.code === 200) {
        this.crossObjArrValue[index].word = ''
        this.crossObjArrValue[index].wordOptionsTwo = res.data
      }
    },

    // 4. 访视选择
    async onInterviewChange(val, index) {
      const params = {
        ...this.searchParams,
        environment: '0',
        visitId: val,
        hasLoading: false,
      }
      const res = await this.getVisitTableListAPI({ params })
      if (res.code === 200) {
        // 清除表和字段
        this.crossObjArrValue[index].form = ''
        this.crossObjArrValue[index].word = ''
        this.crossObjArrValue[index].wordOptions = []
        res.data.forEach(item => {
          item.visitTableName = item.visitTableName || item.tableName
        })
        this.crossObjArrValue[index].formOptions = res.data
      }
    },

    async onInterviewChangeTwo(val, index) {
      const params = {
        ...this.searchParams,
        environment: '0',
        visitId: val,
        hasLoading: false,
      }
      const res = await this.getVisitTableListAPI({ params })
      if (res.code === 200) {
        // 清除表和字段
        this.crossObjArrValue[index].formTwo = ''
        this.crossObjArrValue[index].wordTwo = ''
        this.crossObjArrValue[index].wordOptionsTwo = []
        res.data.forEach(item => {
          item.visitTableName = item.visitTableName || item.tableName
        })
        this.crossObjArrValue[index].formOptionsTwo = res.data
      }
    },

    // 3. 点击增加条件
    btnCrossConditionAddCon() {
      this.crossObjArrValue = btnCrossConditionAddConPublic(this.crossObjArrValue)
    },
    // 2. 点击叉号退出
    btnCrossConditionQuit() {
      this.$refs.tablePartRef.click()
    },
    // 1. 点击跨表条件的省略按钮
    async btnCrossConditionOptions(row) {
      // 1. 记录点击行数据
      this.crossConId = row.id
      // 2. 发送请求
      const params = {
        ...this.searchParams,
        environment: '0',
      }
      const res = await this.getNowConfigVisitAPI({
        params,
      })
      this.interviewOptions = res.data
      res.data.forEach(item => {
        this.interviewOptionseEnums[item.id] = item.visitName
      })
      // 💭设置回显
      if (row.crossTableWeb) {
        this.crossObjArrValue = JSON.parse(row.crossTableWeb.web)
      }
    },
  },
}
</script>
<style lang="scss" scoped></style>
